﻿using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Web;
using TWPure.Token.Model;

namespace TWPure.Token
{

    /// <summary>
    /// 令牌类
    /// </summary>
    public class RayPIToken
    {

        public RayPIToken()
        {
        }

        /// <summary>
        /// 获取JWT字符串
        /// </summary>
        /// <param name="tm"></param>
        /// <param name="expireSliding"></param>
        /// <param name="expireAbsoulte"></param>
        ///  <param name="isCache">是否缓存至本地</param>
        /// <returns></returns>
        public static string IssueJWT(TokenModel tokenModel, TimeSpan expiresSliding, TimeSpan expiresAbsoulte, bool isCache = true)
        {
            DateTime UTC = DateTime.UtcNow;
            Claim[] claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,tokenModel.Sub),//Subject,
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),//JWT ID,JWT的唯一标识
                new Claim(JwtRegisteredClaimNames.Iat, UTC.ToString(), ClaimValueTypes.Integer64),//Issued At，JWT颁发的时间，采用标准unix时间，用于验证过期
            };

            JwtSecurityToken jwt = new JwtSecurityToken(
            issuer: "TWPure",//jwt签发者,非必须
            audience: tokenModel.Uname,//jwt的接收该方，非必须
            claims: claims,//声明集合
            expires: UTC.AddHours(12),//指定token的生命周期，unix时间戳格式,非必须
            signingCredentials: new Microsoft.IdentityModel.Tokens
                .SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes("TWPure's Secret Key")), SecurityAlgorithms.HmacSha256));//使用私钥进行签名加密
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);//生成最后的JWT字符串
            if (isCache)
            {
                RayPIMemoryCache.AddMemoryCache(encodedJwt, tokenModel, expiresSliding, expiresAbsoulte);//将JWT字符串和tokenModel作为key和value存入缓存
            }
            return encodedJwt;
        }
        /// <summary>
        /// 获取JWT字符串(从tokenapi进行获取)
        /// </summary>
        /// <param name="tm"></param>
        /// <param name="expireSliding"></param>
        /// <param name="expireAbsoulte"></param>
        /// <returns></returns>
        public static string TokenForTokenAPI(TokenModel tokenModel)
        {
            SortedDictionary<string, string> sParams = new SortedDictionary<string, string>();
            sParams.Add("tokenModel", JsonConvert.SerializeObject(tokenModel));

            //发送请求
            var reqParamString = sParams.Keys.Aggregate(string.Empty, (current, key) => current + $"{key}={HttpUtility.UrlEncode(sParams[key])}&");
            reqParamString = reqParamString.TrimEnd('&');
            var client = new WebClient();
            //若以后涉及授权校验接口可启用
            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            var postData = Encoding.UTF8.GetBytes(reqParamString);
            var responseData = client.UploadData("http://localhost:8001/api/Token/GetToken", "POST", postData);
            client.Dispose();
            var str = Encoding.UTF8.GetString(responseData);
            return str;
        }
    }
}
